package comp.wxapi.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;

import com.alibaba.fastjson.JSONObject;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RequestUtils {
	
	public static final String MEDIA_TYPE = "application/json";
	
	public static final String GET = "GET";
	
	public static final String POST = "POST";
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtils.class);
	
	private static Request request(String url,String method,String parameter) {
		LOGGER.info("【请求地址】\n{}\n【请求参数】\n{}",url,parameter);
		return new Request.Builder()
				.url(url)
				.method(method, GET.equals(method)?null:RequestBody.create(MediaType.parse(MEDIA_TYPE), parameter))
				.build();
	}
	
	private static Request getConfigRequest(String url) {
		LOGGER.info("【请求地址】\n{}",url);
		return new Request.Builder()
				.url(url)
				.method(GET,null)
				.addHeader("X-Credential-User-Id", "wxapi")
				.build();
	}
	
	private static Request getUaaUserRequest(String url,String header) {
		LOGGER.info("【请求地址】\n{}",url);
		return new Request.Builder()
				.url(url)
				.method(GET,null)
				.addHeader("X-Credential-Token", header)
				.build();
	}
	
	/**
	 * post请求
	 * @param url
	 * @param jsonData
	 * @return
	 */
	public static ResponseBody post(String url,String jsonData) {
		OkHttpClient okHttpClient = new OkHttpClient();
		Call call = okHttpClient.newCall(request(url,POST,jsonData));
		return excute(call);
	}
	
	public static Response setSession(String url,String cookie,String key,String value) {
		JSONObject json = new JSONObject();
		json.put("key", key);
		json.put("value", value);
		String params = json.toJSONString();
		LOGGER.info("【set session json】\n{}",params);
		Request request = new Request.Builder()
		.url(url)
		.method(POST, RequestBody.create(MediaType.parse(MEDIA_TYPE), params))
		.addHeader(HttpHeaders.COOKIE, cookie)
		.build();
		OkHttpClient okHttpClient = new OkHttpClient();
		Call call = okHttpClient.newCall(request);
		try {
			return call.execute();
		} catch (Exception e) {
			LOGGER.error("error",e);
		}
		return null;
	}
	
	public static String getCookie(Response response) {
		try {
			if(response == null) return "";
			return response.header(HttpHeaders.SET_COOKIE);
		} finally {
			IOUtils.closeQuietly(response);
		}
	}
	
	
	/**
	 * get请求
	 * @param url
	 * @param param
	 * @return
	 */
	public static ResponseBody get(String url,Map<String,String> param) {
		OkHttpClient okHttpClient = new OkHttpClient();
		Call call = okHttpClient.newCall(request(url+joinRequestParameter(param),GET,null));
		return excute(call);
	}
	
	/**
	 * 请求微信配置参数
	 * @param url
	 * @param param
	 * @return
	 */
	public static ResponseBody getWxconfig(String url,Map<String,String> param) {
		OkHttpClient okHttpClient = new OkHttpClient();
		Call call = okHttpClient.newCall(getConfigRequest(url+joinRequestParameter(param)));
		return excute(call);
	}
	
	/**
	 * 请求微信配置参数
	 * @param url
	 * @param param
	 * @return
	 */
	public static ResponseBody getUaaUser(String url,Map<String,String> param,String header) {
		OkHttpClient okHttpClient = new OkHttpClient();
		Call call = okHttpClient.newCall(getUaaUserRequest(url+joinRequestParameter(param),header));
		return excute(call);
	}
	
	/**
	 * 请求执行
	 * @param call
	 * @return
	 */
	private static ResponseBody excute(Call call) {
		try {
			Response response = call.execute();
			ResponseBody body = response.body();
			return body;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * get请求参数拼接
	 * @param param
	 * @return
	 */
	private static String joinRequestParameter(Map<String,String> param) {
		if(param == null || param.isEmpty()) return "";
		Set<Entry<String,String>> entrySet = param.entrySet();
		StringBuilder builder = new StringBuilder("?");
		for (Entry<String, String> entry : entrySet) {
			builder.append(entry.getKey())
					.append("=")
					.append(entry.getValue())
					.append("&");
		}
		return builder.substring(0, builder.length()-1).toString();
	}
	
	public static void main(String[] args) throws IOException {
		String url = "http://minio-console.newdao.net/www/anoy_C7C4125BA9B00001F3E7CC701830B8F0";
		ResponseBody body = get(url, null);
		File file = new File("D:\\tmp\\anoy_C7C4125BA9B00001F3E7CC701830B8F0.png");
		BufferedInputStream bis = new BufferedInputStream(body.byteStream());//StorageServiceUtils.getFileInputStream(url)
		FileOutputStream fos = new FileOutputStream(file);
        int b = 0;
        byte[] byArr = new byte[1024];
        while ((b=bis.read(byArr))!=-1) {  
        	fos.write(byArr, 0, b);
        }
        fos.close();
	}
}
